package com.dckj.auto.common.interceptor;

import com.dckj.auto.common.utils.DateUtils;
import com.dckj.auto.common.utils.JsonUtils;
import com.dckj.auto.common.utils.SendMsgUtil;
import com.dckj.auto.common.utils.ehcache.EHCacheUtils;
import com.xiaoleilu.hutool.setting.dialect.Props;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口单设备登陆拦截器
 */
public class ApiInterceptor implements HandlerInterceptor {
    private Props props = new Props("config.properties","UTF-8");
    private String singlePointCacheKey = props.getStr("single_point_cache_key");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String userId = request.getParameter("userId");
        if(StringUtils.isEmpty(userId)){
            return true;
        }
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            SendMsgUtil.sendJsonMessage(response, JsonUtils.error(101,"token is null"));
            return false;
        }
        EHCacheUtils cache = EHCacheUtils.getInstance();
//        User  user = (User) cache.get(token_cache_key, token);
//        if(null == user){
//            user = userService.selectOne(new EntityWrapper<User>().eq("token", token));
//            if(null == user){
//                SendMsgUtil.sendJsonMessage(response, JsonUtils.error(102,"在另一设备登陆"));
//                return false;
//            }
//            cache.put(token_cache_key,token,user);
//        }
//
//        String tokenTime = user.getTokenTime();
        Integer minute = DateUtils.getMinute(DateUtils.getCurrentTime(), "");
        if(minute<0){
            cache.remove(singlePointCacheKey,token);
            SendMsgUtil.sendJsonMessage(response, JsonUtils.error(103,"长时间未登陆"));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }




}
